package com.cj.user.service.file;

import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.nio.file.Files;

/**
 * @Author cheng jun
 * @Description:
 * @Date 2021/7/4 23:34
 */
public class DownLoad {

//    @Resource
//    private UserServices userServices;

    /**
     * 文件下载
     * @param fileId
     * @param response
     * @throws IOException
     */
    public void download(String fileId, String openStyle, HttpServletResponse response) throws IOException {
        // 获取文件信息
//        User user = userServices.getById(fileId);

        // 获取文件输入流
        String realPath = ResourceUtils.getURL("classpath").getPath() + "/static" + "存储路径";
        FileInputStream fileInputStream = new FileInputStream(new File(realPath, "存储新名字"));

        // 打开方式(下载、在线打开)
        openStyle = openStyle == null ? "attachment" : "inline";

        // 设置下载名
        response.setHeader("content-disposition", openStyle + ";fileName=" + URLEncoder.encode("存储旧名字", "UTF-8"));
        // 获取响应输出流
        ServletOutputStream servletOutputStream = response.getOutputStream();

        // 第一种方式：一行行的读
        try {
            byte[] buf = new byte[1024];
            int byteRead;
            while ((byteRead = fileInputStream.read(buf)) != -1) {
                servletOutputStream.write(buf, 0, byteRead);
            }
        } finally {
            fileInputStream.close();
            servletOutputStream.close();
        }

        // 第二种方式：使用FileChannel复制
        /*FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            inputChannel = new FileInputStream(source).getChannel();
            outputChannel = new FileOutputStream(dest).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        } finally {
            inputChannel.close();
            inputChannel.close();
        }*/

        // 第三种方式：文件拷贝（效率最高）
        //FileUtils.copyFile(new File(realPath, "存储名字"), servletOutputStream);

        // 第四种方式：文件拷贝
        IOUtils.copy(fileInputStream, servletOutputStream);
        /*IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(servletOutputStream);*/
        IOUtils.close(fileInputStream);
        IOUtils.close(servletOutputStream);
    }
}